package com.hqd.ch03.v25.utils;

import com.hqd.ch03.v25.aop.Advisor;
import com.hqd.ch03.v25.aop.PointcutAdvisor;
import com.hqd.ch03.v25.aop.framework.aspectj.AbstractAspectJAdvice;
import com.hqd.ch03.v25.aop.framework.aspectj.AspectJAdviceParameterNameDiscoverer;
import com.hqd.ch03.v25.aop.framework.aspectj.AspectJExpressionPointcut;
import com.hqd.ch03.v25.aop.interceptor.ExposeInvocationInterceptor;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

public abstract class AspectJProxyUtils {
    public static boolean isJoinPointRelatedParam(String name) {
        return isJoinPointParam(name) || isStaticPartParam(name);
    }

    public static boolean isJoinPointParam(String name) {
        return StringUtils.equalsAny(name, AspectJAdviceParameterNameDiscoverer.THIS_JOIN_POINT);
    }

    public static boolean isStaticPartParam(String name) {
        return StringUtils.equals(name,
                AspectJAdviceParameterNameDiscoverer.THIS_JOIN_POINT_STATIC_PART);
    }

    public static boolean isVariableName(String name) {
        if (StringUtils.isBlank(name)) {
            return false;
        }
        if (!Character.isJavaIdentifierStart(name.charAt(0))) {
            return false;
        }
        for (int i = 1; i < name.length(); i++) {
            if (!Character.isJavaIdentifierPart(name.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static boolean makeAdvisorChainAspectJCapableIfNecessary(List<Advisor> advisors) {
        if (!advisors.isEmpty()) {
            boolean foundAspectJAdvice = false;
            for (Advisor advisor : advisors) {
                if (isAspectJAdvice(advisor)) {
                    foundAspectJAdvice = true;
                    break;
                }
            }
            if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {
                advisors.add(0, ExposeInvocationInterceptor.ADVISOR);
                return true;
            }
        }
        return false;
    }

    private static boolean isAspectJAdvice(Advisor advisor) {
        return (advisor.getAdvice() instanceof AbstractAspectJAdvice ||
                (advisor instanceof PointcutAdvisor &&
                        ((PointcutAdvisor) advisor).getPointcut() instanceof AspectJExpressionPointcut));
    }
}
